﻿public class NetHandler_Visit : GameServerMessageHandler
{
    public const string Key = "Visit";

    public static NetHandler_Visit NewHandler()
    {
        return new NetHandler_Visit();
    }

    protected override ISerialize NewData() => new FromToUserRequestData();

    public override void _Execute(TCPClient client, ISerialize _data)
    {
        FromToUserRequestData requestData = _data as FromToUserRequestData;

        GameDebug.Log($"{client.userID} 用户{requestData.fromUserId} 访问:{requestData?.toUserId}  time:{(long)CommonFunctions.GetTimeStampSeconds()}");

        UserServer user = Game.instance.GetUser(client.userID);

        VisitResponseData response = new VisitResponseData();

        if (user == null)
        {
            GameDebug.LogError($"找不到用户：{client.userID}");
            response.code = ErrorCode.UserNotFound;
        }
        else
        {
            if (requestData != null)
            {
                visits exist = UserServer.FindInVisitTable(requestData.fromUserId, requestData.toUserId);
                int totalCount = 0;
                if(exist != null)
                {
                    totalCount = exist.total_visit_count;
                }
                totalCount++;

                Visit newVisit = new Visit();
                newVisit.userId = requestData.toUserId;
                newVisit.totalVisitCount = totalCount;
                newVisit.lastVisitTime = (long)CommonFunctions.GetTimeStampSeconds();
                response.visit = newVisit;

                long opponent = requestData.toUserId;
                UserServer opponentUser = Game.instance.GetUser(opponent);
                if (opponentUser != null)
                {
                    newVisit.userId = requestData.fromUserId;
                    opponentUser.data.AddVisitor(newVisit);

                    GameDebug.Log($"给{opponent} 发送申请结果事件");
                    NetEvent_Visit netEvent_Visit = new NetEvent_Visit();
                    netEvent_Visit.visitData = new VisitData();
                    netEvent_Visit.visitData.visitor = newVisit;

                    netEvent_Visit.SendToRemote(opponentUser.client);
                }

                int ret = visits.SetVisit(requestData.fromUserId, requestData.toUserId, newVisit.totalVisitCount, newVisit.lastVisitTime);
                
                if (ret >= 0)
                    response.code = 0;
                else
                    response.code = -1;
            }
            else
            {
                GameDebug.LogError($"requestData == null _data:{_data != null} type:{_data.GetType()}");
                response.code = -1;
            }
        }

        byte[] data = response.Write();
        this.SendResponse(client, Key, this.m_MessageReceived.seq, data);
    }
}
